package com.peng.leetcode.tree;

/**
 * MaxAncestorDiff1
 * 1026. 节点与其祖先之间的最大差值
 * https://leetcode.cn/problems/maximum-difference-between-node-and-ancestor/
 *
 * @author: lupeng6
 * @create: 2023/2/8 18:02
 */
public class MaxAncestorDiff1 {
    int ans = Integer.MIN_VALUE;

    public int maxAncestorDiff(TreeNode root) {
        dfs1(root);
        return ans;
    }

    void dfs1(TreeNode root) {
        if (root == null) {
            return;
        }
        dfs(root.left, root.val);
        dfs(root.right, root.val);
        dfs1(root.left);
        dfs1(root.right);
    }

    void dfs(TreeNode n, int val) {
        if (n == null) {
            return;
        }
        ans = Math.max(ans, Math.abs(val - n.val));
        dfs(n.left, val);
        dfs(n.right, val);
    }
}
